const { code } = require('../utils/stateModel')
const User = require('../db/models/userSchema')
const Counter = require('../db/models/counterSchema')
const pagerFun = require('../utils/pager')
const { successModel, errorModel } = require("../utils/stateModel")

// 登录
const login = async ({ username, password }) => {
  const loginstate = await User.findOne({ username, password },
    'userId username realname userEmail mobile sex roleNames')
  if (loginstate) {
    return loginstate
  }
  return false
}

// 注册用户
const register = async (ctx, params) => {
  const res = await User.findOne({ username: params.username })
  if (res) {
    ctx.body = new errorModel("该账户已经注册")
    return
  }
  const { TXCODE, confirmPassword, ...other } = params;
  const user = await new User({
    userId: 0,
    ...other
  })
  await user.save();
  ctx.body = {
    errorCode: "0000",
    message: "注册成功"
  }
}

const userlist = async (username, mobile, pageNum, pageSize) => {
  let params = {}
  let pager = {}
  if (username) params.username = username
  if (mobile) params.mobile = mobile
  const query = User.find(params,
    'userId username realname userEmail mobile password sex roleNames')
  const userList = await query.skip(pagerFun(pageNum, pageSize).skipIndex).limit(pagerFun(pageNum, pageSize).pager.pageSize)
  const total = await User.countDocuments(params)
  // pager.total = total
  // pager.pageNum = parseInt(pageNum)
  if (userList) return { userList, total }
  return false
}

const createFirstUser = async (params) => {
  const res = await User.findOne({ username: "admin" })
  if (res) {
    return
  }
  const user = await new User({
    userId: 0, ...params
  })
  await user.save();

}

// 更新用户信息
const updateUserList = async (ctx, { _id, ...params }) => {
  try {
    const userListItem = await User.findOneAndUpdate({ _id }, { ...params })
    if (userListItem) {
      ctx.body = new successModel({
        userListItem,
        successMessage: "用户信息更新"
      })
      return
    }
  } catch (error) {
    ctx.body = new errorModel("用户编辑失败")
    return
  }
}

// 新增用信息 
const updateaddlist = async (ctx, { _id, action, ...params }) => {
  if (action) {
    try {
      const userList = await User.findOneAndUpdate({ _id }, { ...params })
      if (userList) {
        ctx.body = new successModel("修改成功")
        return
      }
      return ctx.body = new errorModel("修改失败")
    } catch (error) {
      ctx.body = new errorModel(error.message)
      return
    }

  }
  //新增用户
  if (!params.username || !params.mobile || !params.userEmail || !params.password) {
    ctx.body = new errorModel('参数错误', code.PARAM_ERROR)
    return
  }
  const res = await User.findOne({ $or: [{ username: params.username }, { userEmail: params.userEmail }] })
  if (res) {
    ctx.body = new errorModel(`新增用户名已存在:用户名:${res.username}邮箱:${res.userEmail}`)
    return
  }
  try {
    //这一步运行一次就可以注释掉，自增需要有个初始值
    const res = await Counter.findOne({ id: "userId" })
    if (!res) {
      await Counter.create({
        "id": "userId",
        "sequence_value": 1
      })
    }
    //处理自增userId
    const count = await Counter.findOneAndUpdate({ id: 'userId' }, { $inc: { sequence_value: 1 } }, { new: true })
    const user = await new User({
      userId: count.sequence_value, ...params
    })
    await user.save();
    ctx.body = new successModel('新增成功')
  } catch (error) {
    ctx.body = new errorModel(`新增失败${error}`, code.DB_ERROR)
  }
}

//删除用户（一般删除用户并非真正删除，而是改变状态，这里使用了真正的删除）
const dellist = async (ctx, { _id }) => {
  if (!_id) {
    ctx.body = new errorModel("参数错误", code.PARAM_ERROR)
    return
  }
  //_id接收数组
  try {
    const res = await User.deleteMany({ _id: { $in: _id } })
    ctx.body = new successModel(`删除成功${res.deletedCount}条`)
  } catch (error) {
    ctx.body = new errorModel("删除失败", code.DB_ERROR)
  }
}

module.exports = {
  login,
  userlist,
  updateaddlist,
  dellist,
  createFirstUser,
  register,
  updateUserList
}